package cc.rengu.redp.bizimpl.upmp.service.impl;

import cc.rengu.redp.bizimpl.enums.BizDataAuditStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizDataStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizOprEnum;
import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.dao.TradeAreaInfoMapper;
import cc.rengu.redp.bizimpl.upmp.domain.BizTmp;
import cc.rengu.redp.bizimpl.upmp.domain.TradeAreaInfo;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpOrganization;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpPrivilegeCheck;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.OperationResult;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.utils.SortUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author 刘玉亮.LL
 */
@Service
@DS("upmp")
public class TradeAreaInfoServiceImpl extends ServiceImpl<TradeAreaInfoMapper, TradeAreaInfo> implements ITradeAreaInfoService {
    @Autowired
    private IBizTmpService bizTmpService;

    @Autowired
    private IBizHisService bizHisService;

    @Autowired
    private IUpmpSysSeqService upmpSysSeqService;

    @Autowired
    private IUpmpOrganizationService organizationService;

    @Autowired
    private IUpmpSysParamService upmpSysParamService;

    @Autowired
    private IUpmpPrivilegeCheckService authPrivilegeCheckService;

    @Autowired
    private TradeAreaInfoMapper tradeAreaInfoMapper;

    @Override
    public IPage<TradeAreaInfo> findByPage(QueryRequest request, TradeAreaInfo info) {
        try {
            LambdaQueryWrapper<TradeAreaInfo> queryWrapper = new LambdaQueryWrapper<>();
            // 当前登录用户
            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            String instId = info.getInstId();
            if (null != user && user.isAdmin()) {
                if (StringUtils.isBlank(instId)) {
                    instId = user.getInstId();
                    queryWrapper.likeRight(TradeAreaInfo::getInstId, info.getInstId());
                }
            } else {
                instId = user.getInstId();
//                queryWrapper.in(TradeAreaInfo::getCrtOrgId,  GZIPUtils.uncompressToString(user.getUserOrgCodes());
            }
            queryWrapper.likeRight(TradeAreaInfo::getInstId, instId);
            if (StringUtils.isNotBlank(info.getTradeAreaCode())) {
                queryWrapper.likeRight(TradeAreaInfo::getTradeAreaCode, info.getTradeAreaCode());
            }
            if (StringUtils.isNotBlank(info.getTradeAreaName())) {
                queryWrapper.likeRight(TradeAreaInfo::getTradeAreaName, info.getTradeAreaName());
            }
            if (StringUtils.isNotBlank(info.getBelongInstId())) {
                queryWrapper.likeRight(TradeAreaInfo::getBelongInstId, info.getBelongInstId());
            }
            if (StringUtils.isNotBlank(info.getTradeAreaStatus())) {
                queryWrapper.likeRight(TradeAreaInfo::getTradeAreaStatus, info.getTradeAreaStatus());
            }
            Page<TradeAreaInfo> page = new Page<>();
            IPage<TradeAreaInfo> retPage = this.tradeAreaInfoMapper.findByPage(page,info);
            SortUtil.handlePageSort(request, page, true);
            return retPage;
        } catch (Exception e) {
            log.error("查询失败", e);
            return null;
        }
    }
    @Override
    public OperationResult saveData(String menuId, String oprMenuName, TradeAreaInfo entity, HttpServletRequest request, String webNextUrl) throws RedpException {
        Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        String optFlag = request.getParameter("optFlag") == null ? "" : request.getParameter("optFlag");
        String lastUpddt = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
                // 获取当前登录用户信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        String instId = entity.getInstId();
        String crtOrgId = "";

        if(optFlag.equals("add")&&user.isAdmin()){
            if(StringUtils.isEmpty(instId)){
                log.error("保存数据时请先选择法人行!");
                return OperationResult.buildFailureResult("保存数据时请先选择法人行!");
            }else{
                UpmpOrganization headOrg=organizationService.getHeadOrgByCode(instId);
                crtOrgId=(headOrg==null?user.getOrgCode():headOrg.getOrgCode());
            }
        }else{
            instId=(instId==null?user.getInstId():instId);
            crtOrgId=(entity.getCrtOrgId()==null?user.getOrgCode():entity.getCrtOrgId());
        }
        UpmpOrganization org = organizationService.getOrgByCode(crtOrgId, instId);
        entity.setLastOprId(user.getId());
        entity.setLastUpdateTime(lastUpddt);

        TradeAreaInfo oldEntity = null;
        if (!PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(optFlag)){
            oldEntity = this.getById(entity.getId());
        }
        //新增
        if(PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(optFlag)){
            entity.setId(null);
            entity.setTradeAreaCode(generateCode(instId));
            entity.setOprId(user.getId());
            entity.setCrtOrgId(org.getOrgCode());
            entity.setCreateTime(lastUpddt);

            //获取审核信息
            UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "商圈管理:新增");
            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                //需要审核
                entity.setAuditStatus(BusinessContainer.status_01);
                entity.setTradeAreaStatus(BusinessContainer.agentStatus_00);
                QueryWrapper queryWrapper=new QueryWrapper();
                queryWrapper.eq("TRADE_AREA_NAME",entity.getTradeAreaName());
                List list = this.list(queryWrapper);
                if (list.size()>0){
                    log.error("商圈名已存在！");
                    return OperationResult.buildFailureResult("商圈名已存在！");
                }
                //保存entity TMP
                this.saveOrUpdate(entity);

                bizTmpService.saveBizTmp(entity,user,org.getInstId(), BizOprEnum.OPR_ADD.getType(),lastUpddt,
                        menuId,oprMenuName,entity.getTradeAreaStatus(),entity.getAuditStatus(),entity.getId(),webNextUrl,null,null,null);
            } else {
                entity.setAuditStatus(BusinessContainer.status_02);
                entity.setTradeAreaStatus(BusinessContainer.agentStatus_01);
                QueryWrapper queryWrapper=new QueryWrapper();
                queryWrapper.eq("TRADE_AREA_NAME",entity.getTradeAreaName());
                List list = this.list(queryWrapper);
                if (list.size()>0){
                    log.error("商圈名已存在！");
                    return OperationResult.buildFailureResult("商圈名已存在！");
                }
                //保存 entity His
                this.saveOrUpdate(entity);
                bizHisService.saveBizHisNew(entity,entity,user,org.getInstId(),BizOprEnum.OPR_ADD.getType(),lastUpddt,menuId,oprMenuName, entity.getId(),null,null,null);
            }
        } else if(PageOptFlagEnum.OPT_FLAG_UPDATE.getType().equals(optFlag)){
            //获取审核信息
            UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "商圈管理:修改");
            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                //修改的数据存入临时表，正式表仅修改状态
                TradeAreaInfo tradeAreaInfo = this.getById(entity.getId());
                tradeAreaInfo.setAuditStatus(BusinessContainer.status_41);

                QueryWrapper queryWrapper=new QueryWrapper();
                queryWrapper.eq("TRADE_AREA_NAME",entity.getTradeAreaName());
                List list = this.list(queryWrapper);
                if (list.size()>0){
                    log.error("商圈名已存在！");
                    return OperationResult.buildFailureResult("商圈名已存在！");
                }
                //保存 entity TMP
                this.saveOrUpdate(tradeAreaInfo);

                bizTmpService.saveBizTmp(entity,user,org.getInstId(),BizOprEnum.OPR_UPDATE.getType(),lastUpddt,
                        menuId,oprMenuName,BusinessContainer.agentStatus_00,tradeAreaInfo.getAuditStatus(),entity.getId(), webNextUrl,null,null,null);

            } else {
                //保存正式表  His
                entity.setAuditStatus(BusinessContainer.status_42);
                entity.setTradeAreaStatus(BusinessContainer.agentStatus_01);
                QueryWrapper queryWrapper=new QueryWrapper();
                queryWrapper.eq("TRADE_AREA_NAME",entity.getTradeAreaName());
                List list = this.list(queryWrapper);
                if (list.size()>0){
                    log.error("商圈名已存在！");
                    return OperationResult.buildFailureResult("商圈名已存在！");
                }
                //保存 entity his
                this.saveOrUpdate(entity);
                bizHisService.saveBizHisNew(entity,oldEntity,user,org.getInstId(),BizOprEnum.OPR_UPDATE.getType(),lastUpddt,menuId,oprMenuName, entity.getId(),null,null,null);

            }
        } else if (PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(optFlag)) {

            //获取审核信息
            UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "商圈管理:注销");
            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                entity.setAuditStatus(BusinessContainer.status_11);

                this.saveOrUpdate(entity);
                bizTmpService.saveBizTmp(entity,user,org.getInstId(),BizOprEnum.OPR_CANCEL.getType(),lastUpddt,
                        menuId,oprMenuName,BusinessContainer.agentStatus_00,entity.getAuditStatus(),entity.getId(), webNextUrl,null,null,null);
            } else {
                entity.setAuditStatus(BusinessContainer.status_12);
                entity.setTradeAreaStatus(BusinessContainer.agentStatus_03);
                this.saveOrUpdate(entity);
                bizHisService.saveBizHisNew(entity,oldEntity,user,org.getInstId(),BizOprEnum.OPR_CANCEL.getType(),lastUpddt,
                        menuId,oprMenuName, entity.getId(),null,null,null);
            }
        } else if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag)) {
            String impStatus = entity.getTradeAreaStatus();
            String auditStatus = entity.getAuditStatus();
            //获取临时表数据并转换成实体对象
            BizTmp tmp = bizTmpService.getById(entity.getId());
            if (Common.isBlank(tmp)) {
                log.error("根据id没有找到指定临时表数据！");
                return OperationResult.buildFailureResult("根据id没有找到指定临时表数据！", result);
            }
            String bizdata = "";
            if (null != tmp.getBizData1()) {
                bizdata += tmp.getBizData1();
            }
            if (null != tmp.getBizData2()) {
                bizdata += tmp.getBizData2();
            }
            if (null != tmp.getBizData3()) {
                bizdata += tmp.getBizData3();
            }
            TradeAreaInfo tradeAreaInfo = JSON.parseObject(bizdata, TradeAreaInfo.class);

            String opt = request.getParameter("opt");
            if (Common.isBlank(opt)) {
                log.error("请求参数(opt)异常!");
                return OperationResult.buildFailureResult("请求参数(opt)异常!", result);
            }

            String bizOpr = "";
            if (BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType().equals(entity.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    auditStatus = BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType();
                    impStatus = BizDataStatusEnum.STATUS_NORMAL.getType();
                } else {
                    auditStatus = BizDataAuditStatusEnum.AUDIT_STATUS_ADD_REJECT.getType();
                    impStatus=BizDataStatusEnum.STATUS_DRAFT.getType();
                }
                bizOpr = BizOprEnum.OPR_ADD.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_CHECKING.getType().equals(entity.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    auditStatus = BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_PASS.getType();
                    impStatus = BizDataStatusEnum.STATUS_CANCELED.getType();
                } else {
                    auditStatus = BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_REJECT.getType();
                }
                bizOpr = BizOprEnum.OPR_CANCEL.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_STOP_CHECKING.getType().equals(entity.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    auditStatus = BizDataAuditStatusEnum.AUDIT_STATUS_STOP_PASS.getType();
                    impStatus = BizDataStatusEnum.STATUS_STOPED.getType();
                } else {
                    auditStatus = BizDataAuditStatusEnum.AUDIT_STATUS_STOP_REJECT.getType();
                }
                bizOpr = BizOprEnum.OPR_STOP.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_USE_CHECKING.getType().equals(entity.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    auditStatus = BizDataAuditStatusEnum.AUDIT_STATUS_USE_PASS.getType();
                    impStatus = BizDataStatusEnum.STATUS_NORMAL.getType();
                } else {
                    impStatus = BizDataAuditStatusEnum.AUDIT_STATUS_USE_REJECT.getType();
                }
                bizOpr = BizOprEnum.OPR_USE.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType().equals(entity.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    auditStatus = BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType();
                    impStatus = BizDataStatusEnum.STATUS_NORMAL.getType();
                } else {
                    auditStatus = BizDataAuditStatusEnum.AUDIT_STATUS_UPD_REJECT.getType();
                }
                bizOpr = BizOprEnum.OPR_UPDATE.getType();
            }


            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                // 将临时表数据同步到正式表
                tradeAreaInfo.setAuditStatus(auditStatus);
                tradeAreaInfo.setTradeAreaStatus(impStatus);
                BeanUtils.copyProperties(tradeAreaInfo, entity);
                entity.setAuditRefuseReason(request.getParameter("auditRefuseReason"));
                this.saveOrUpdate(entity);
                // 审批通过将正式表更新到历史表
                bizHisService.saveBizHisNew(entity,oldEntity, user, org.getInstId(), bizOpr, lastUpddt, menuId, oprMenuName, entity.getId(),null,null,null);
            } else {
                entity.setTradeAreaStatus(impStatus);
                entity.setAuditStatus(auditStatus);
                entity.setAuditRefuseReason(request.getParameter("auditRefuseReason"));
                this.saveOrUpdate(entity);
                impStatus=BizDataStatusEnum.STATUS_DRAFT.getType();
            }
            // 修改临时表的审核状态等字段
            bizTmpService.saveBizTmp(entity, user, org.getInstId(), bizOpr, lastUpddt, menuId, oprMenuName, !Common.isBlank(impStatus) ? impStatus : entity.getTradeAreaStatus(), auditStatus, entity.getId(), webNextUrl,null,null,null);
        }


        result.put("id", entity.getId());
        return OperationResult.buildSuccessResult("数据保存处理完成", result);
    }
    @Override
    public OperationResult chkData(String menuId, String oprMenuName, TradeAreaInfo entity, HttpServletRequest request, String webNextUrl) throws RedpException {
        Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        String id = request.getParameter("id");
        result.put("id", id);
                // 获取当前登录用户信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        UpmpOrganization org = organizationService.getOrgByCode(user.getOrgCode(),user.getInstId());
        String optFlag = request.getParameter("optFlag");
        SimpleDateFormat fmtdt = new SimpleDateFormat("yyyyMMddHHmmss");
        String lastUpddt = fmtdt.format(new Date());
        entity.setLastOprId(user.getId());
        entity.setLastUpdateTime(lastUpddt);

        TradeAreaInfo oldEntity = this.getById(entity.getId());

        // 审批通过
        if ("pass".equals(optFlag)) {
            // 审批流程中
            if (BusinessContainer.status_01.equals(entity.getAuditStatus())) {
                entity.setAuditStatus(BusinessContainer.status_02); // 状态置为审批通过
                entity.setTradeAreaStatus(BusinessContainer.agentStatus_01);
                this.saveOrUpdate(entity);
                bizHisService.saveBizHisNew(entity,oldEntity,user,org.getInstId(),BizOprEnum.OPR_ADD.getType(),lastUpddt,menuId,oprMenuName, entity.getId(),null,null,null);
            }
            // 修改 - 审批流程中
            if (BusinessContainer.status_41.equals(entity.getAuditStatus())) {
                BizTmp tmp = bizTmpService.getById(id);
                if (Common.isBlank(tmp)) {
                    log.error("根据id没有找到指定临时表数据！");
                    return OperationResult.buildFailureResult("根据id没有找到指定临时表数据！", result);
                }
                String bizdata = "";
                if (null != tmp.getBizData1()) {
                    bizdata += tmp.getBizData1();
                }
                if (null != tmp.getBizData2()) {
                    bizdata += tmp.getBizData2();
                }
                if (null != tmp.getBizData3()) {
                    bizdata += tmp.getBizData3();
                }
                TradeAreaInfo tradeAreaInfo = JSON.parseObject(bizdata, TradeAreaInfo.class);
                BeanUtils.copyProperties(tradeAreaInfo, entity);
                entity.setAuditStatus(BusinessContainer.status_42);
                entity.setTradeAreaStatus(BusinessContainer.agentStatus_01);

                //保存 entity TMP
                this.saveOrUpdate(entity);
                bizHisService.saveBizHisNew(entity,oldEntity,user,org.getInstId(),BizOprEnum.OPR_UPDATE.getType(),lastUpddt,menuId,oprMenuName, entity.getId(),null,null,null);

            }
            // 注销-审批流程中
            if (BusinessContainer.status_11.equals(entity.getAuditStatus())) {
                entity.setAuditStatus(BusinessContainer.status_12);
                entity.setTradeAreaStatus(BusinessContainer.agentStatus_03);
                this.saveOrUpdate(entity);
                bizHisService.saveBizHisNew(entity,oldEntity,user,org.getInstId(),BizOprEnum.OPR_CANCEL.getType(),lastUpddt,menuId,oprMenuName, entity.getId(),null,null,null);
            }

            //处理临时表
            BizTmp tmp = bizTmpService.getById(entity.getId());
            tmp.setBizStatus(entity.getTradeAreaStatus());
            tmp.setAuditStatus(BusinessContainer.agentStatus_01);
            bizTmpService.save(tmp);
        }
        // 审批退回
        if ("back".equals(optFlag)) {
            // 状态
            String status = entity.getAuditStatus();

            // 注销-审批流程中
            if (BusinessContainer.status_11.equals(status)) {
                entity.setAuditStatus(BusinessContainer.status_13); // 注销-审批拒绝
                entity.setTradeAreaStatus(BusinessContainer.agentStatus_01);
            }
            // 新增-审批流程中
            if (BusinessContainer.status_01.equals(status)) {
                entity.setAuditStatus(BusinessContainer.status_03); // 新增-审批拒绝
                entity.setTradeAreaStatus(BusinessContainer.agentStatus_01);
            }
            // 修改-审批流程中
            if (BusinessContainer.status_41.equals(status)) {
                entity.setAuditStatus(BusinessContainer.status_43); // 修改-审批拒绝
                entity.setTradeAreaStatus(BusinessContainer.agentStatus_01);
            }
            try {
                this.saveOrUpdate(entity);
                BizTmp tmp = bizTmpService.getById(entity.getId());
                tmp.setBizStatus(entity.getTradeAreaStatus());
                tmp.setAuditStatus(BusinessContainer.agentStatus_01);
                bizTmpService.save(tmp);
                if (log.isDebugEnabled()) {
                    log.debug("保存id为：" + id + "的记录成功");
                }
            } catch (Exception e) {
                log.error("保存id为：" + id + "的记录失败", e);
                return OperationResult.buildFailureResult("处理失败！", result);
            }
        }

        return OperationResult.buildSuccessResult("数据保存处理完成", result);
    }

    private String generateCode(String instId) {
        // 获取渠道ID：固定20
        String channelId = CommonUtils.getChannelId(upmpSysParamService,instId);
        // 代理商编码前缀：AG
        String prefix = BusinessContainer.CircleCd_PREFIX;
        // 自动生成一级代码
        String paramCode = BusinessContainer.COMM_PARAM_CODE;
        // 生成序列号
        String seqNum = upmpSysSeqService.updateParamValue(paramCode, "TradeAreaInfo", channelId);
        // 代理商编码
        String result = prefix + instId.substring(instId.length()-3) + String.format("%03d", Integer.parseInt(seqNum));
        return result;
    }

    @Override
    public TradeAreaInfo findOneByCode(String mchntarea, String status,String instId) {
        LambdaQueryWrapper<TradeAreaInfo>wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(TradeAreaInfo::getTradeAreaCode,mchntarea);
        wrapper.eq(TradeAreaInfo::getTradeAreaStatus,status);
        wrapper.eq(TradeAreaInfo::getInstId,instId);
        return  this.getOne(wrapper);
    }
}
